var contentType = require('content-type')
var getRawBody = require('raw-body')
var convert = require('xml-js');
var crypto = require('crypto')

class WeixinController {

  async replay(ctx) {
    let xml = await getRawBody(ctx.req, {
      length: ctx.req.headers['content-length'],
      limit: '1mb',
      encoding: contentType.parse(ctx.req).parameters.charset
    })
    let obj = convert.xml2js(xml, {
      compact: true,
      textKey: 'value',
      cdataKey: 'value'
    }).xml;

    let replayObj = Object.keys(obj).reduce((item, key) => {
      item[key] = obj[key]['value'];
      return item;
    }, {})

    console.log('replay:', replayObj)
    let str = '<a href="http://www.web678.xyz/index.html">vip8</a>'
    ctx.body = `
    <xml>
      <ToUserName><![CDATA[${replayObj.FromUserName}]]></ToUserName>
      <FromUserName><![CDATA[${replayObj.ToUserName}]]></FromUserName>
      <CreateTime>${new Date().toLocaleString()}</CreateTime>
      <MsgType><![CDATA[text]]></MsgType>
      <Content><![CDATA[${str}]]></Content>
    </xml>
    `
  }


  auth(ctx) {
    console.log(ctx.query)
    let token = 'weixin';
    let { timestamp, nonce,signature,echostr } = ctx.query;
    // let str = `nonce=${nonce}&timestamp=${timestamp}&token=${token}`
    // console.log('str:',str)
    let str = [token, timestamp, nonce].sort().join('')
    let mySignature = crypto.createHash('sha1').update(str).digest('hex')
    console.log('mySignature:', mySignature,signature)
    if(mySignature === signature){
      ctx.body = echostr;
    }else{
      ctx.body = '非常访问';
    }
  }

}


module.exports = new WeixinController();